package com.org.oracle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.org.oracle.mysql.entity.UserDailyStudyTime;
import com.org.oracle.mapper.UserDailyStudyTimeMapper;
import com.org.oracle.result.Result;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.org.oracle.service.UserDailyStudyTimeService;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * (UserDailyStudyTime)表服务实现类
 *
 * @author luo
 * @since 2024-12-16 21:22:13
 */
@Service("userDailyStudyTimeService")
public class UserDailyStudyTimeServiceImpl extends ServiceImpl<UserDailyStudyTimeMapper, UserDailyStudyTime> implements UserDailyStudyTimeService {

    @Resource
    private UserDailyStudyTimeMapper userDailyStudyTimeMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public Result getTotalStudyTimeInMinutes(String uid) {
        long totalStudyTimeInMillis = getAccumulatedStudyTimeUntilNow(uid);
        return Result.ok(totalStudyTimeInMillis / (1000 * 60)) ;
    }

    /**
     * 获取截止到当前的累计刷题时间（包含数据库中历史所有记录以及Redis中暂存题目累计用时）
     *
     * @param userId 用户ID
     * @return 累计刷题时间（单位：毫秒）
     */
    private long getAccumulatedStudyTimeUntilNow(String userId) {
        // 先从数据库中获取所有历史刷题时间记录并累加
        long accumulatedStudyTimeFromDb = getTotalAccumulatedStudyTime(userId);

        // 从 Redis 中获取所有暂存题目累计用时并累加
        Set<String> allTemporaryKeys = redisTemplate.keys("temporary_question_time:" + userId + ":*");
        long accumulatedStudyTimeFromRedis = 0;
        if (allTemporaryKeys!= null &&!allTemporaryKeys.isEmpty()) {
            for (String key : allTemporaryKeys) {
                Object cachedObj = redisTemplate.opsForValue().get(key);
                Long cachedQuestionTime = 0L;
                if (cachedObj instanceof Number) {
                    cachedQuestionTime = ((Number) cachedObj).longValue();
                }
                accumulatedStudyTimeFromRedis += cachedQuestionTime;
            }
        }
        return accumulatedStudyTimeFromDb + accumulatedStudyTimeFromRedis;
    }

    private Long getTotalAccumulatedStudyTime(String userId) {
        QueryWrapper<UserDailyStudyTime> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", userId);
        List<UserDailyStudyTime> dailyStudyTimeList = userDailyStudyTimeMapper.selectList(queryWrapper);
        long accumulatedStudyTime = 0;
        for (UserDailyStudyTime record : dailyStudyTimeList) {
            accumulatedStudyTime += record.getTotalStudyTime();
        }
        return accumulatedStudyTime;
    }
    /**
     * 获取用户当日刷题时间（返回给前端是分钟为单位），若没有该用户的当日记录则默认返回零
     *
     * @param uid 用户ID
     * @return 包含用户当日刷题时间（分钟为单位）的Result对象
     */
    @Override
    public Result getTodayStudyTimeInMinutes(String uid) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        Date sqlDate = java.sql.Date.valueOf(currentDate);

        QueryWrapper<UserDailyStudyTime> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", uid).eq("date", sqlDate);
        // 查询该用户当日的刷题时间记录
        UserDailyStudyTime record = userDailyStudyTimeMapper.selectOne(queryWrapper);

        long totalStudyTimeInSeconds = 0;
        if (record!= null) {
            // 如果有记录，获取当日刷题总时长，数据库的是毫秒
            totalStudyTimeInSeconds = record.getTotalStudyTime();
        }
        // 从 Redis 中获取当天暂存题目累计用时并累加
        Set<String> todayTemporaryKeys = redisTemplate.keys("temporary_question_time:" + uid + ":*");
        if (todayTemporaryKeys!= null &&!todayTemporaryKeys.isEmpty()) {
            for (String key : todayTemporaryKeys) {
                Object cachedObj = redisTemplate.opsForValue().get(key);
                Long cachedQuestionTime = 0L;
                if (cachedObj instanceof Number) {
                    cachedQuestionTime = ((Number) cachedObj).longValue();
                }
                totalStudyTimeInSeconds += cachedQuestionTime / 1000;
            }
        }
        // 毫秒转为分钟，除以60000
        long totalStudyTimeInMinutes = totalStudyTimeInSeconds / (60*1000);

        return Result.ok(totalStudyTimeInMinutes);
    }
}

